package com.salt.modules.sys.web;

import com.alibaba.fastjson.JSONObject;
import com.google.api.client.util.Lists;
import com.salt.common.json.AjaxJson;
import com.salt.common.kit.FileKit;
import com.salt.common.utils.Merge;
import com.salt.common.utils.StringUtils;
import com.salt.core.log.annotation.OperationRecord;
import com.salt.core.oss.OssTemplate;
import com.salt.core.oss.model.SaltFile;
import com.salt.core.persistence.Page;
import com.salt.core.web.BaseController;
import com.salt.modules.sys.entity.MultiTenant;
import com.salt.modules.sys.entity.SystemFile;
import com.salt.modules.sys.entity.User;
import com.salt.modules.sys.service.MultiTenantService;
import com.salt.modules.sys.service.SystemFileService;
import com.salt.modules.sys.utils.UserUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description TNPM文件处理Controller
 * @Author salt
 * @Date 2021-04-16
 * @Version 1.0.1
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sys/config/file")
public class SystemFileController extends BaseController {

    private final OssTemplate ossTemplate;
    private final SystemFileService systemFileService;
    private final MultiTenantService multiTenantService;


    @PostMapping("upload")
    public AjaxJson upload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        AjaxJson ajaxJson = new AjaxJson();
        if (!file.isEmpty()) {
            SaltFile saltFile = ossTemplate.putFile(file);
            ajaxJson.put("url",saltFile.getOuterLink());
        }
        return ajaxJson;
    }

    @PostMapping("uploadFiles")
    public AjaxJson uploadFiles(HttpServletRequest request, HttpServletResponse response, @RequestParam("files") MultipartFile[] files) {
        AjaxJson ajaxJson = new AjaxJson();
        if (files.length > 0) {
            List<String> urlList = Lists.newArrayList();
            Arrays.stream(files).forEach( file -> {
                SaltFile saltFile = ossTemplate.putFile(file);
                urlList.add(saltFile.getOuterLink());
            });
            ajaxJson.put("urlList", urlList);
        }
        return ajaxJson;
    }

    @PostMapping("uploadFile")
    public AjaxJson uploadFile(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        AjaxJson ajaxJson = new AjaxJson();
        if (!file.isEmpty()) {
            String fileSize = FileKit.getFileSize(file.getSize());
            SaltFile saltFile = ossTemplate.putFile(file);
            saltFile.setType(FileKit.getFileType(saltFile.getName()));
            saltFile.setSize(fileSize);
            ajaxJson.put("saltFile",saltFile);
        }
        return ajaxJson;
    }

    @PostMapping("uploadList")
    public AjaxJson uploadList(HttpServletRequest request, HttpServletResponse response, @RequestParam("files") MultipartFile[] files) {
        AjaxJson ajaxJson = new AjaxJson();
        if (files.length > 0) {
            List<SaltFile> fileList = Lists.newArrayList();
            Arrays.stream(files).forEach( file -> {
                String fileSize = FileKit.getFileSize(file.getSize());
                SaltFile saltFile = ossTemplate.putFile(file);
                saltFile.setType(FileKit.getFileType(saltFile.getName()));
                saltFile.setSize(fileSize);
                fileList.add(saltFile);
            });
            ajaxJson.put("fileList", fileList);
        }
        return ajaxJson;
    }

    @GetMapping("list")
    public AjaxJson list(SystemFile systemFile) {
        return AjaxJson.success().put("list", systemFileService.findList(systemFile));
    }

    @GetMapping("page")
    public AjaxJson page(SystemFile systemFile,
                         HttpServletRequest request, HttpServletResponse response) {
        User user = UserUtils.getUser();
        if (!user.isAdmin()) { // 是不是超级管理员
            MultiTenant multiTenant = multiTenantService.find(new MultiTenant(user));
            if (multiTenant != null) {  // 是不是具有多租户权限
                systemFile.setTenantIds(multiTenant.getTenanIds());
            } else {  // 不是超级管理员也不具有租户权限
                systemFile.setTenant(user.getCompany().getId());
            }
        }
        Page<SystemFile> page =
                systemFileService.findPage(new Page<>(request, response),systemFile);
        return AjaxJson.success().put("page", page);
    }

    @PostMapping("save")
    @OperationRecord(service = "系统服务", module = "系统文件", operation = "新增", description = "")
    public AjaxJson save(String fileJson) {
        if (StringUtils.isBlank(fileJson)) {
            return AjaxJson.error("保存失败!");
        }
        List<SaltFile> fileList = JSONObject.parseArray(fileJson, SaltFile.class);
        if (fileList != null && !fileList.isEmpty()) {
            SystemFile systemFile = null;
            User user = UserUtils.getUser();
            ArrayList<SystemFile> insertFileList = Lists.newArrayList();
            for (SaltFile saltFile:fileList) {
                systemFile = new SystemFile();
                systemFile.setTenant(user.getCompany().getId());
                systemFile.setOriginalName(saltFile.getOriginalName());
                systemFile.setName(saltFile.getName());
                String suffix = StringUtils.substringAfterLast(systemFile.getName(), ".");
                systemFile.setSuffix(Merge.string(".",suffix));
                systemFile.setSize(saltFile.getSize());
                systemFile.setType(saltFile.getType());
                systemFile.preInsert();
                insertFileList.add(systemFile);
            }
            systemFileService.insertBatch(insertFileList);
        }
        return AjaxJson.success("保存成功");
    }

    @PostMapping("update")
    public AjaxJson update(SystemFile systemFile) {
        if (StringUtils.isNotBlank(systemFile.getId())) {
            systemFileService.save(systemFile);
            return AjaxJson.success("保存成功!");
        }
        return AjaxJson.error("保存失败!");
    }

    @GetMapping("queryById")
    public AjaxJson queryById(String id) {
        return AjaxJson.success().put("systemFile", systemFileService.get(id));
    }

    @PostMapping("find")
    public AjaxJson find(SystemFile systemFile) {
        return AjaxJson.success().put("systemFile", systemFileService.find(systemFile));
    }

    @DeleteMapping("delete")
    @OperationRecord(service = "系统服务", module = "系统文件", operation = "删除", description = "")
    public AjaxJson delete(SystemFile systemFile) {
        if (StringUtils.isNotBlank(systemFile.getId())) {
            systemFileService.delete(systemFile);
            return AjaxJson.success("删除成功!");
        }
        return AjaxJson.error("删除失败!");
    }

    @GetMapping("download")
    @OperationRecord(service = "系统服务", module = "系统文件", operation = "下载", description = "")
    public AjaxJson download(SystemFile systemFile, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isNotBlank(systemFile.getName()) && StringUtils.isNotBlank(systemFile.getOriginalName())) {
            ossTemplate.downloadFile(request, response, systemFile.getOriginalName(), systemFile.getName());
            return AjaxJson.success();
        }
        return AjaxJson.error("下载失败");
    }

    @GetMapping("template")
    @OperationRecord(service = "系统服务", module = "系统文件", operation = "模版下载", description = "")
    public AjaxJson templateDownload(String label, HttpServletRequest request, HttpServletResponse response) {
        SystemFile systemFile = systemFileService.find(new SystemFile(label));
        if (systemFile != null &&
                StringUtils.isNotBlank(systemFile.getName()) &&
                StringUtils.isNotBlank(systemFile.getOriginalName())) {
            ossTemplate.downloadFile(request, response, systemFile.getOriginalName(), systemFile.getName());
            return AjaxJson.success();
        }
        return AjaxJson.error("下载失败");
    }

}
